﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//表示一个小球
public class Ball : MonoBehaviour
{
    public BallData CurrentBallData { get; private set; }

    Vector2 moveForce;
    Vector3 brakeForce;
    Vector2 jumpForce;
    PhysicsMaterial2D physicsMaterial2D;
    new Rigidbody2D rigidbody2D;
    SpriteRenderer spriteRenderer;
    bool jumpable = true;
    float radius;
    private void Awake()
    {
        rigidbody2D = GetComponent<Rigidbody2D>();
        spriteRenderer = GetComponent<SpriteRenderer>();
        CurrentBallData = ScriptableObject.CreateInstance<BallData>();
        CurrentBallData.BallColor = spriteRenderer.color;
        physicsMaterial2D = new PhysicsMaterial2D();
        //physicsMaterial2D = rigidbody2D.sharedMaterial;
       // rigidbody2D.sharedMaterial = physicsMaterial2D;
    }
    public void SetBall()
    {
        rigidbody2D.velocity *= rigidbody2D.mass / CurrentBallData.Mass;//动量不变
        rigidbody2D.mass = CurrentBallData.Mass;
        rigidbody2D.angularDrag = CurrentBallData.AngularDrag;
        rigidbody2D.drag = CurrentBallData.MoveDrag;

        spriteRenderer.color = CurrentBallData.BallColor;

        physicsMaterial2D.bounciness = CurrentBallData.Bouncness;
        rigidbody2D.sharedMaterial = physicsMaterial2D;//这里必须要赋值
        moveForce = CurrentBallData.MovePower * Vector2.right;
        brakeForce = CurrentBallData.BrakePower * Vector2.right;
        jumpForce = CurrentBallData.JumpImpulse * Vector2.up;

        Vector3 pos = transform.position;
        radius = transform.localScale.y / 2f;
        pos.y -= transform.localScale.y / 2f;
        pos.y += radius;
        transform.position = pos;
        gameObject.layer = CurrentBallData.Layer;
    }
    //在FixedUpdate中调用
    public void Move(float hor)
    {
        if (!jumpable) hor = 0f;
        if (Mathf.Sign(hor) != Mathf.Sign(rigidbody2D.velocity.x))
            rigidbody2D.AddForce(hor * brakeForce);
        else rigidbody2D.AddForce(hor * moveForce);
    }
    //在Update中调用
    public void Jump(bool jump)
    {
        Jumpable();
        if (jumpable && jump)
        {
            rigidbody2D.AddForce(jumpForce, ForceMode2D.Impulse);
        }
    }
    protected void Jumpable()
    {
        jumpable = Physics2D.Raycast(transform.position, Vector2.down, radius + 0.05f, Physics2D.AllLayers, Constants.RayCastMinDepth);
    }
    IEnumerator SetBouncinessZero()
    {
        float bounciness = physicsMaterial2D.bounciness;
        physicsMaterial2D.bounciness = 0f;
        yield return new WaitForSeconds(Time.fixedDeltaTime * 2.5f);
        physicsMaterial2D.bounciness = bounciness;
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.layer == Constants.Layer_MetumAbsorb_St)
        {
            //StartCoroutine(SetBouncinessZero());
            rigidbody2D.velocity = Vector2.zero;
        }
    }
}
